import React, { useEffect, useRef, useState } from "react";
import Header from "../../components/Header";
import "./style.scss";
import { data } from "react-router-dom";
const user_id = 1;
const server_id = 45643453;
// 1. 创建 WebSocket 对象
const ws = new WebSocket(
  `ws://124.221.74.149:8003/koa/ws?user_id=${user_id}&server_id=${server_id}`
);
const Chat = () => {
  const [list, setList] = useState([]);
  const [message, setMessage] = useState("");

  useEffect(() => {
    // 2. 连接成功时触发
    ws.addEventListener("open", () => {
      console.log("服务器连接成功");

      // 3. 向服务器发送消息  获取聊天记录
      ws.send(
        JSON.stringify({
          type: "getChatList",
        })
      );
    });

    // 4. 接收服务器的消息
    ws.addEventListener("message", (e) => {
      console.log("收到服务器消息：", JSON.parse(e.data));
      const { type, data } = JSON.parse(e.data);
      if (type === "getChatList") {
        setList(data);
      } else if (type === "addMessage") {
        setList((list) => [...list, data]);
      }
    });
  }, []);

  const submit = () => {
    ws.send(JSON.stringify({
      type: 'addMessage', 
      data: {
        user_id,
        server_id,
        message,
        dir: 1  
      }
    }));

  
  };  
  const chatListRef = useRef()

  useEffect(() => {
    document.documentElement.scrollTop = 1000000000
    // chatListRef.current.scrollTop = 1000000000
  }, [list])


  return (
    <div>
      <Header title="客服"></Header>

      <div className="chat-list" ref={chatListRef}>
        {list.map((v, i) => {
          const customClassName =
            v.dir !== 1 ? "chat-list-item-left" : "chat-list-item-right";
          
            const avatar = v.dir === 1 ? v.user_avatar : v.server_avatar;
          return (
            <div className={customClassName} key={i}>
              <img src={avatar} className="avatar" alt="" />
              <div className="content">{v.message}</div>
            </div>
          );
        })}
      </div>
      <div className="bottom">
        <input
          type="text"
          value={message}
          onChange={(e) => setMessage(e.target.value)}
        />
        <button onClick={() => submit()}>发送</button>
      </div>
    </div>
  );
};

export default Chat;
